using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Text;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.UI;
using Microsoft.MediaCenter.TV.Scheduling;

namespace MCEMediaManager
{
    public class EpgPlugin : MediaPlugin, IMediaPlugin
    {
        private VirtualList _SearchResults;
        private IList _DiscoveryResults;

        public override string Name
        {
            get
            {
                return "Guide";
            }
        }

        public override bool HasSearchInterface
        {
            get { return true; }
        }

        public VirtualList SearchResults
        {
            get
            {
                if (_SearchResults == null)
                {
                    _SearchResults = new VirtualList();
                }
                return (this._SearchResults);
            }
            set { this._SearchResults = value; }
        }

        public override IList GetSearchResults(string filter)
        {
            return (IList)_SearchResults;
        }

        public override int SearchResultsCount
        {
            get
            {
                return SearchResults.Count;
            }
            set
            {
                if (_SearchResultsCount != value)
                {
                    _SearchResultsCount = value;
                    FirePropertyChanged("SearchResultsCount");
                    FirePropertyChanged("SearchLabel");
                }
            }
        }

        public override string SearchLabel
        {
            get
            {
                return this.Name + " (" + SearchResultsCount + ")";
            }
            set
            {
                base.SearchLabel = value;
            }
        }

        public override void SearchByName(object obj)
        {
            //while (Application.Current.EpgData.CurrentStatus == EpgStatus.Loading)
            //{
            //    Thread.Sleep(2000);
            //}
            //if (Application.Current.EpgData.EpgData != null)
            //{
            //    SearchArgs args = (SearchArgs)obj;
            //    MceEpgDataSet.programsRow[] programRows = (MceEpgDataSet.programsRow[])Application.Current.EpgData.EpgData.programs.Select("title like '%" + args.SearchPage.SearchText.Replace("'", "''") + "%'");
            //    Microsoft.MediaCenter.UI.Application.DeferredInvoke(delegate { SearchResults.Clear(); });
            //    foreach (MceEpgDataSet.programsRow program in programRows)
            //    {
            //        DataRow[] tempScheduledEntries = program.GetscheduleentriesRows();// Application.Current.EpgData.EpgData.scheduleentries.Select("program = " + program.identifier);
            //        Microsoft.MediaCenter.UI.Application.DeferredInvoke(new DeferredHandler(AddItemToSearchResults), new EpgArgs(program, tempScheduledEntries));
            //    }
            //}
        }

        public void AddItemToSearchResults(object obj)
        {
            //EpgArgs args = (EpgArgs)obj;
            //MceEpgDataSet.programsRow program = args.ProgramRow;
            //MceEpgDataSet.scheduleentriesRow[] scheduledEntries = (MceEpgDataSet.scheduleentriesRow[]) args.ScheduledEntries;
            //EpgMediaItem mediaItem = new EpgMediaItem();
            //mediaItem.Name = program.title;
            //mediaItem.Description = program.description;
            //mediaItem.ID = program.identifier;
            //mediaItem.EpisodeName = program.episodetitle;
            //mediaItem.IsEpisodic = program.isepisodic;
            //mediaItem.OriginalAirDate = program.originalairdate;
            //mediaItem.SeriesID = program.seriesid;
            //mediaItem.Year = program.year;
            //mediaItem.Plugin = this;
            //bool foundScheduledEntry = false;
            //foreach (MceEpgDataSet.scheduleentriesRow scheduledEntry in scheduledEntries)
            //{
            //    bool isEntryValid = false;
            //    foreach (MceEpgDataSet.servicelineupsRow serviceLineup in scheduledEntry.servicesRow.GetservicelineupsRows())
            //    {
            //        if (serviceLineup.isavailable)
            //            isEntryValid = true;
            //    }
            //    if (isEntryValid)
            //    {
            //        GuideEntry tempEntry = new GuideEntry();
            //        tempEntry.Affiliation = scheduledEntry.servicesRow.affiliation;
            //        tempEntry.CallSign = scheduledEntry.servicesRow.callsign;
            //        tempEntry.EndTime = scheduledEntry.servicesRow.endtime;
            //        tempEntry.ServiceName = scheduledEntry.servicesRow.servicename;
            //        tempEntry.StartTime = scheduledEntry.servicesRow.starttime;
            //        tempEntry.VirtualChannelNumber = scheduledEntry.servicesRow.virtualchannelnumber;
            //        mediaItem.Entries.Add(tempEntry);
            //        foundScheduledEntry = true;
            //    }
            //}
            //if(foundScheduledEntry)
            //    SearchResults.Add(mediaItem);
        }

        public override void OnDetailsActionInvoked(DetailsCommand command)
        {
            base.OnDetailsActionInvoked(command);
            //EpgMediaItem item = (EpgMediaItem)command.Owner;
            //ScheduleRequest request = null;
            //switch (command.Type)
            //{
            //    case "RecordShow":
            //        CreateScheduleRequestResult scheduleResult = CreateScheduleRequestResult.NoConfiguredResource;
            //        scheduleResult = Application.Current.RecordShow("EpgPlugin : Record " + item.Name, item.Name, item.Entries[0].CallSign, item.Entries[0].StartTime, false, out request);
            //        //if (scheduleResult == CreateScheduleRequestResult.NotFound)
            //        //{
            //        //    scheduleResult = Application.Current.RecordShow("MeeVee Plugin : Record " + item.Name, "", item.ChannelName, item.StartTime, false, out request);
            //        //    if (scheduleResult == CreateScheduleRequestResult.NotFound)
            //        //        scheduleResult = Application.Current.RecordShow("MeeVee Plugin : Record " + item.Name, item.Name, "", item.StartTime, false, out request);
            //        //}
            //        //if (scheduleResult == CreateScheduleRequestResult.ScheduledNoConflict)
            //        //{
            //        //    if (request.GetScheduleEvents().Count == 0)
            //        //        request.Cancel();
            //        //}
            //        break;
            //    case "RecordSeries":
            //        //Application.Current.RecordShow("MeeVee Plugin : Record Series " + item.Name, item.Name, item.ChannelName, item.StartTime, true, out request);
            //        break;
            //    case "SearchOnline":
            //        Application.Current.GoToAddTorrentPage(item.Name);
            //        break;
            //}
        }
    
    }

    public class EpgMediaItem : MediaItem, IMediaItem
    {
        #region Private Properties
        private int _ID;
        private string _EpisodeName;
        private bool _IsEpisodic;
        private DateTime _OriginalAirDate;
        private string _SeriesID;
        private int _Year;
        private List<GuideEntry> _Entries;
        #endregion


        #region Public Properties
        public int ID
        {
            get { return (this._ID); }
            set { this._ID = value; }
        }

        public string EpisodeName
        {
            get { return (this._EpisodeName); }
            set { this._EpisodeName = value; }
        }

        public bool IsEpisodic
        {
            get { return (this._IsEpisodic); }
            set { this._IsEpisodic = value; }
        }

        public DateTime OriginalAirDate
        {
            get { return (this._OriginalAirDate); }
            set { this._OriginalAirDate = value; }
        }

        public string SeriesID
        {
            get { return (this._SeriesID); }
            set { this._SeriesID = value; }
        }

        public int Year
        {
            get { return (this._Year); }
            set { this._Year = value; }
        }
        public List<GuideEntry> Entries
        {
            get 
            {
                if (this._Entries == null)
                    this._Entries = new List<GuideEntry>();
                return (this._Entries); 
            }
            set { this._Entries = value; }
        }
        public override string ListDisplayProperties
        {
            get
            {
                return @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Segeo;}}{\colortbl ;\red255\green255\blue255;}{\*\generator Msftedit 5.41.21.2508;}\viewkind4\uc1\pard\cf1\b\f0\fs28 Name\b0  : " + Name + @"\par\par\b Episode\b0 : " + EpisodeName + @" \par\par\b Original Air Date\b0 : " + OriginalAirDate.ToLocalTime().ToString("MM/dd/yyyy hh:mm tt") + @"\par}";
            }
        }
        public override string ListDisplayDescription
        {
            get
            {
                string returnString = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Segeo;}}{\colortbl ;\red255\green255\blue255;}{\*\generator Msftedit 5.41.21.2508;}\viewkind4\uc1\pard\cf1\f0\fs28 " + Description + @"\par\par\b Episodes\b0 \par ";
                foreach (GuideEntry entry in Entries)
                {
                    returnString += entry.CallSign + " at " + entry.StartTime.ToLocalTime().ToString("M/d/yyyy h:mm tt") + @"\par ";
                }
                returnString += @"}";
                return returnString;
            }
        }
        public override ArrayListDataSet Commands
        {
            get
            {
                if (_Commands == null)
                {
                    _Commands = new ArrayListDataSet(this);

                    _Commands.Add(Plugin.CreateCommand(this, "Record Show", "RecordShow", this.Name));
                    _Commands.Add(Plugin.CreateCommand(this, "Record Series", "RecordSeries", this.Name));
                    //_Commands.Add(Plugin.CreateCommand(this, "Search Online", "SearchOnline", this.Name));
                }
                return _Commands;
            }
        }

        #endregion

    }

    public class GuideEntry
    {
        private DateTime _StartTime;
        private DateTime _EndTime;
        private string _CallSign;
        private string _Affiliation;
        private string _ServiceName;
        private int _VirtualChannelNumber;


        public string ServiceName
        {
            get { return (this._ServiceName); }
            set { this._ServiceName = value; }
        }

        public string Affiliation
        {
            get { return (this._Affiliation); }
            set { this._Affiliation = value; }
        }

        public string CallSign
        {
            get { return (this._CallSign); }
            set { this._CallSign = value; }
        }

        public DateTime StartTime
        {
            get { return (this._StartTime); }
            set { this._StartTime = value; }
        }

        public DateTime EndTime
        {
            get { return (this._EndTime); }
            set { this._EndTime = value; }
        }

        public int VirtualChannelNumber
        {
            get { return (this._VirtualChannelNumber); }
            set { this._VirtualChannelNumber = value; }
        }
    }

    public class EpgArgs
    {
        //public EpgArgs(MceEpgDataSet.programsRow newProgramRow, DataRow[] newScheduledEntries)
        //{
        //    ProgramRow = newProgramRow;
        //    ScheduledEntries = newScheduledEntries;
        //}

        //private MceEpgDataSet.programsRow _ProgramRow;

        //public MceEpgDataSet.programsRow ProgramRow
        //{
        //    get { return (this._ProgramRow); }
        //    set { this._ProgramRow = value; }
        //}

        //private DataRow[] _ScheduledEntries;

        //public DataRow[] ScheduledEntries
        //{
        //    get { return (this._ScheduledEntries); }
        //    set { this._ScheduledEntries = value; }
        //}

    }
}
